# -*- coding: utf-8 -*-
from kivy.core.audio import SoundLoader
from kivy.logger import Logger
from constants import TIME_UP_SOUND, LAST_SECONDS_FINISHED_SOUND


class Sounds:
    """Enumeration of all possible sounds in game"""
    LongBeep, ShortBeep, Timeout, ExtendedTimeout,\
        WordGuessed, WordFailed, WordReturned = range(7)


class BaseSoundManager(object):
    def __init__(self):
        self.muted = False

    def configure(self, config):
        pass

    def mute(self, mute):
        self.muted = mute

    def play(self, sound):
        pass


class SoundManager(BaseSoundManager):
    def __init__(self):
        super(SoundManager, self).__init__()
        self.sounds = {}
        self.sound_paths = {}

    def register(self, sound, path):
        if (sound in self.sound_paths):
            if self.sound_paths[sound] == path:
                return
        if path == 'No sound':
            if sound in self.sound_paths:
                del self.sounds[sound]
                del self.sound_paths[sound]
            return
        self.sound_paths[sound] = path
        self.sounds[sound] = SoundLoader.load(path)

    def load_from_settings(self, sound):
        self.register(Sounds.WordFailed, sound.sound_failed)
        self.register(Sounds.WordGuessed, sound.sound_guessed)
        self.register(Sounds.WordReturned, sound.sound_put_back)
        self.mute(not sound.sound_on)

    def configure(self, settings):
        self.register(Sounds.ShortBeep, 'sounds/short_sound.wav')
        self.register(Sounds.LongBeep, 'sounds/long_sound.wav')
        self.register(Sounds.Timeout, TIME_UP_SOUND)
        self.register(Sounds.Timeout, LAST_SECONDS_FINISHED_SOUND)
        self.load_from_settings(settings.sound)

        settings.sound.add_observer(self.load_from_settings)

    def play(self, sound):
        if self.muted:
            return
        if sound in self.sounds:
            self.sounds[sound].play()
        else:
            Logger.warn('No sound to play %s' % (sound,))


class MockSoundManager(BaseSoundManager):
    pass
